#include "myserialport.h"

//Search the serial port and set the name of it
QString MySerialPort::SeekSerialPort()
{
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        serial.setPortName(info.portName());
        return info.description()+"("+info.portName()+")";
    }
    return "未检测到串口";
}

// Set the parameters of the serial port
void MySerialPort::SetSerialPortParameter(uint8_t BaudRateIndx)
{
    switch (BaudRateIndx) {
    case 0:serial.setBaudRate(QSerialPort::Baud115200,QSerialPort::AllDirections);
        break;
    case 1:serial.setBaudRate(QSerialPort::Baud57600,QSerialPort::AllDirections);
        break;
    case 2:serial.setBaudRate(QSerialPort::Baud38400,QSerialPort::AllDirections);
        break;
    case 3:serial.setBaudRate(QSerialPort::Baud19200,QSerialPort::AllDirections);
        break;
    case 4:serial.setBaudRate(QSerialPort::Baud9600,QSerialPort::AllDirections);
        break;
    case 5:serial.setBaudRate(QSerialPort::Baud4800,QSerialPort::AllDirections);
        break;
    case 6:serial.setBaudRate(QSerialPort::Baud2400,QSerialPort::AllDirections);
        break;
    case 7:serial.setBaudRate(QSerialPort::Baud1200,QSerialPort::AllDirections);
        break;
    default:
        break;
    }
    serial.setDataBits(QSerialPort::Data8);
    serial.setParity(QSerialPort::NoParity);
    serial.setFlowControl(QSerialPort::NoFlowControl);
    serial.setStopBits(QSerialPort::OneStop);
}

void MySerialPort::SetSerialPortParameter_1(uint8_t BaudRateIndx)
{

   serial_1.setBaudRate(QSerialPort::Baud115200,QSerialPort::AllDirections);
    serial_1.setDataBits(QSerialPort::Data8);
    serial_1.setParity(QSerialPort::NoParity);
    serial_1.setFlowControl(QSerialPort::NoFlowControl);
    serial_1.setStopBits(QSerialPort::OneStop);
}

//Open the serial port
bool MySerialPort::OpenSerialPort()
{
    bool isOpen;
    isOpen=serial.open(QIODevice::ReadWrite);
    if( isOpen)
    {
        connect(&serial,SIGNAL(readyRead()),this,SLOT(ReadAllDatas()));
    }
    else serial.close();
    return isOpen;
}

bool MySerialPort::OpenSerialPort_1()
{
    bool isOpen;
    isOpen=serial_1.open(QIODevice::ReadWrite);
    if( isOpen)
    {
        connect(&serial_1,SIGNAL(readyRead()),this,SLOT(ReadAllDatas_1()));
    }
    else serial_1.close();
    return isOpen;
}

//Close the serial port
void MySerialPort::CloseSerialPort()
{
    serial.close();
}

void MySerialPort::CloseSerialPort_1()
{
    serial_1.close();
}

// Write data
void MySerialPort::SendDatas(QByteArray data)
{
    serial.write(data);
}

void MySerialPort::SendDatas_1(QByteArray data)
{
    serial_1.write(data);
}

//Read all the data
void MySerialPort::ReadAllDatas()
{
    QByteArray data;
    data=serial.readAll();
    //if(!data.isEmpty())
        //emit SerialPassDatas(data);
}
void MySerialPort::ReadAllDatas_1()
{
    QByteArray data;
    data=serial_1.readAll();
    if(!data.isEmpty())
        emit SerialPassDatas(data);
}

